<template>
  <el-popover
    v-model="visible"
    placement="bottom"
    trigger="click"
    :visible-arrow="false"
    style="margin-top:0px;"
  >
    <div class="col-controller">
      <div class="title">
        <el-checkbox v-model="checkAll" :indeterminate="indeterminate" style="display:inline-block;font-weight:bold" @change="handleCheckAll">全选</el-checkbox>
        <div class="close" style="display:inline-block; float:right;"><i class="el-icon-close" @click="close" /><i class="el-icon-check" @click="confirm" /></div>
      </div>
      <div style="height:1px; background-color:#dcdfe6;" />
      <el-checkbox-group v-model="selectedCols" @change="handleCheckChange">
        <el-checkbox v-for="(item, i) in value" :key="i" :label="item.prop">{{ item.label }}</el-checkbox>
      </el-checkbox-group>
    </div>
    <el-button slot="reference" style="padding: 5px 7px;">
      <svg-icon icon-class="columns" style="font-size:18px" />
      <i class="el-icon-caret-bottom" />
    </el-button>
  </el-popover>
</template>

<script>
export default {
  props: {
    value: {
      type: Array,
      required: true
    },
    tableKey: {
      type: String,
      default: 'key'
    }
  },
  data() {
    const selColsStr = window.localStorage.getItem(this.tableKey)
    const selCols = selColsStr && JSON.parse(selColsStr) || this.value.filter(item => item.show).map(item => item.prop)
    const tempList = [...this.value]
    tempList.forEach(item => {
      item.show = selCols.includes(item.prop)
    })
    this.$emit('input', [...tempList])
    return {
      visible: false,
      checkAll: this.value.findIndex(item => !item.show) === -1,
      indeterminate: this.value.findIndex(item => !item.show) !== -1 && this.value.findIndex(item => item.show) !== -1,
      selectedCols: selCols
    }
  },
  methods: {
    handleCheckAll(val) {
      this.selectedCols = val ? this.value.map(item => item.prop) : []
      this.indeterminate = false
    },
    handleCheckChange(val) {
      const checkedCount = val.length
      this.checkAll = checkedCount === this.value.length
      this.indeterminate = checkedCount > 0 && checkedCount < this.value.length
    },
    close() {
      this.visible = false
    },
    confirm() {
      const tempList = [...this.value]
      tempList.forEach(item => {
        item.show = this.selectedCols.includes(item.prop)
      })
      this.$emit('input', [...tempList])
      window.localStorage.setItem(this.tableKey, JSON.stringify(this.selectedCols))
      this.visible = false
    }
  }
}
</script>

<style lang="scss">
.col-controller .el-checkbox{
  display: block;
  margin: 10px;
}
</style>

<style lang="scss" scoped>
.col-controller {
  .title {
    .close{
      display:inline-block;
      line-height:39px;
      i {
        border:1px solid #dcdfe6;
        margin-right:5px;
        cursor:pointer;
        &:hover{
          border:1px solid #1890FF;
          color:#1890FF;
        }
      }
    }
  }
}
</style>
